package com.goldsprite.projecttemplategenerator.testold;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileExtractor {

	public static void main(String[] args) {
		String zipFilePath = "resources/project-template.zip"; // ZIP 文件路径
		String destDirectory = "resources/extracted-template"; // 解压目标目录

		try {
			unzip(zipFilePath, destDirectory);
			System.out.println("解压完成: " + destDirectory);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void unzip(String zipFilePath, String destDirectory) throws IOException {
		File destDir = new File(destDirectory);
		// 如果目标目录不存在，创建它
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		unzip(destDir, zipFilePath);
	}

	public static File unzip(File file, String destDirectory) throws IOException {
		return unzip(file, destDirectory, null);
	}
	public static File unzip(File file, String destDirectory, UnzipCallback callback) throws IOException {
		String zipFilePath = file.getAbsolutePath();
		long totalFiles = 0;

		// 计算 ZIP 文件中条目的总数（用于进度报告）
		try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
			while (zipIn.getNextEntry() != null) {
				totalFiles++;
			}
		}

		long processedFiles = 0;
		try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath))) {
			ZipEntry entry;

			// 遍历 ZIP 文件中的所有条目
			while ((entry = zipIn.getNextEntry()) != null) {
				String filePath = destDirectory + File.separator + entry.getName();

				if (entry.isDirectory()) {
					// 如果条目是目录，创建目录
					new File(filePath).mkdirs();
				} else {
					// 如果条目是文件，解压文件
					extractFile(zipIn, filePath);
				}

				// 更新已处理文件数并调用回调
				processedFiles++;
				if (callback != null) {
					callback.onProgress(entry.getName(), processedFiles, totalFiles);
				}

				zipIn.closeEntry();
			}
		}

		return new File(destDirectory);
	}

	private static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
		File file = new File(filePath);
		File parentDir = file.getParentFile();
		if (parentDir != null && !parentDir.exists()) {
			parentDir.mkdirs();
		}

		try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
			byte[] buffer = new byte[4096];
			int bytesRead;
			while ((bytesRead = zipIn.read(buffer)) != -1) {
				bos.write(buffer, 0, bytesRead);
			}
		}
	}

	public interface UnzipCallback {
		void onProgress(String currentFile, long processedFiles, long totalFiles);
	}

}

